<template>
  <div class="article-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文章列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="refreshList">刷新</el-button>
          </div>
        </div>
      </template>
      
      <!-- 文章列表表格 -->
      <el-table 
        :data="tableData" 
        v-loading="loading"
        style="width: 100%"
        border
        size="small"
        :header-cell-style="{ background: 'transparent' }"
      >
        <el-table-column prop="title" label="文章标题" >
          <template #default="scope">
            <span class="article-title">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="publisher" label="发布者"  />
        
        <el-table-column prop="publishTime" label="发布时间" >
          <template #default="scope">
            <span>{{ formatDate(scope.row.publishTime) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
         <el-table-column label="操作" width="360px">
           <template #default="scope">
             <div class="action-buttons">
               <!-- 浏览按钮 - 所有状态都显示 -->
               <el-button 
                 size="small" 
                 type="info" 
                 link
                 @click="handleView(scope.row)"
               >
                 浏览
               </el-button>
               
               <!-- 已删除状态(status=2)只显示浏览按钮 -->
               <template v-if="scope.row.status !== 2">
                 <el-button 
                   size="small" 
                   type="primary" 
                   link
                   @click="handleEdit(scope.row)"
                 >
                   修改
                 </el-button>
                 <el-button 
                   size="small" 
                   type="danger" 
                   link
                   @click="handleDelete(scope.row)"
                 >
                   删除
                 </el-button>
                <!-- 状态为待发布(0)时显示开启按钮 -->
                <el-button 
                  v-if="scope.row.status === 0"
                  size="small" 
                  type="success"
                  link
                  @click="handleEnableArticle(scope.row)"
                >
                  开启
                </el-button>
                
                <!-- 状态为已发布(1)时显示关闭按钮 -->
                <el-button 
                  v-if="scope.row.status === 1"
                  size="small" 
                  type="warning"
                  link
                  @click="handleDisableArticle(scope.row)"
                >
                  关闭
                </el-button>
               </template>
             </div>
           </template>
         </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 文章详情侧边栏 -->
    <el-drawer
      v-model="drawerVisible"
      title="文章详情"
      size="60%"
      direction="rtl"
      :show-close="true"
      :modal="true"
    >
      <div v-if="articleDetail" class="article-detail">
        <div class="detail-header">
          <h2 class="article-title-detail">{{ articleDetail.title }}</h2>
          <div class="article-meta">
            <el-tag :type="getStatusType(articleDetail.status)" size="small">
              {{ getStatusText(articleDetail.status) }}
            </el-tag>
            <span class="meta-info">作者：{{ articleDetail.publisher }}</span>
            <span class="meta-info" v-if="articleDetail.publishTime">
              发布时间：{{ formatDate(articleDetail.publishTime) }}
            </span>
          </div>
        </div>
        
        <!-- 封面图片 -->
        <div v-if="articleDetail.articleCover" class="article-cover">
          <img :src="articleDetail.articleCover" alt="文章封面" />
        </div>
        
        <!-- 文章内容 -->
        <div class="article-content">
          <div class="content-title">文章内容</div>
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="viewerEditorRef"
              :defaultConfig="viewerToolbarConfig"
              :mode="viewerMode"
            />
            <Editor
              style="height: 400px; overflow-y: auto;"
              v-model="viewerHtml"
              :defaultConfig="viewerEditorConfig"
              :mode="viewerMode"
              @onCreated="handleViewerCreated"
            />
          </div>
        </div>
      </div>
      
      <div v-else class="loading-container">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
        <span>加载中...</span>
      </div>
    </el-drawer>
    
    <!-- 开启文章时间选择对话框 -->
    <el-dialog
      v-model="publishTimeDialogVisible"
      title="选择发布时间"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="publish-time-dialog">
        <div class="dialog-content">
          <p class="dialog-tip">请选择文章的发布时间（不选择则立即发布）</p>
          
          <!-- 时间选择器 -->
          <div class="publish-time-container">
            <el-date-picker
              v-model="selectedPublishTime"
              type="datetime"
              placeholder="选择发布时间（不选择则立即发布）"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :clearable="true"
              class="custom-datepicker"
              style="width: 100%;"
            />
            
            <!-- 快捷时间选择按钮 -->
            <div class="quick-time-buttons">
              <el-button 
                size="small" 
                @click="setQuickTime(1)"
                :type="isQuickTimeSelected(1) ? 'primary' : 'default'"
              >
                1小时后
              </el-button>
              <el-button 
                size="small" 
                @click="setQuickTime(4)"
                :type="isQuickTimeSelected(4) ? 'primary' : 'default'"
              >
                4小时后
              </el-button>
              <el-button 
                size="small" 
                @click="setQuickTime(10)"
                :type="isQuickTimeSelected(10) ? 'primary' : 'default'"
              >
                10小时后
              </el-button>
              <el-button 
                size="small" 
                @click="clearPublishTime"
                :type="!selectedPublishTime ? 'primary' : 'info'"
              >
                立即发布
              </el-button>
            </div>
          </div>
          
          <div class="publish-time-tips">
            <p>不选择时间将立即发布文章</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="publishTimeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEnableArticle">确认开启</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, shallowRef, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getArticleList, getArticleDetail, deleteArticle, enableArticle, disableArticle } from '@/api/article'

// 路由
const router = useRouter()

// 加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])

// 分页配置
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0
})

// 侧边栏相关
const drawerVisible = ref(false)
const articleDetail = ref(null)

// 开启文章时间选择对话框
const publishTimeDialogVisible = ref(false)
const selectedPublishTime = ref('')
const currentEnableArticle = ref(null)

// 查看器编辑器实例
const viewerEditorRef = shallowRef()
const viewerMode = 'default'
const viewerHtml = ref('')

// 查看器工具栏配置（只读模式，移除编辑功能）
const viewerToolbarConfig = {
  toolbarKeys: []  // 空数组，不显示工具栏
}

// 查看器编辑器配置（只读）
const viewerEditorConfig = {
  placeholder: '文章内容...',
  readOnly: true  // 设置为只读
}

// 获取文章列表
const fetchArticleList = async () => {
  loading.value = true
  try {
    const response = await getArticleList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize
    })
    
    console.log('文章列表响应:', response)
    
    if (response) {
      tableData.value = response.list || []
      pagination.total = response.totals || 0
      pagination.totalPages = response.totalPages || 0
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败，请重试')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  fetchArticleList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNo = 1
  fetchArticleList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.pageNo = page
  fetchArticleList()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return dateString
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待发布
    case 1: return 'success'  // 已发布
    case 2: return 'danger'   // 已删除
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待发布'
    case 1: return '已发布'
    case 2: return '已删除'
    default: return '未知'
  }
}

// 记录查看器编辑器实例
const handleViewerCreated = (editor) => {
  viewerEditorRef.value = editor
}

// 浏览文章
const handleView = async (row) => {
  try {
    drawerVisible.value = true
    articleDetail.value = null
    
    const response = await getArticleDetail(row.id)
    console.log('文章详情响应:', response)
    
    if (response) {
      articleDetail.value = response
      // 设置编辑器内容
      viewerHtml.value = response.content || ''
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败，请重试')
    drawerVisible.value = false
  }
}

// 编辑文章
const handleEdit = (row) => {
  console.log('点击编辑按钮，文章ID:', row.id)
  // 跳转到发布页面，并传递文章ID
  router.push({
    path: '/article/publish',
    query: { id: row.id }
  }).then(() => {
    console.log('路由跳转成功')
  }).catch(err => {
    console.error('路由跳转失败:', err)
  })
}

// 删除文章
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认删除文章"${row.title}"吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除接口
    await deleteArticle(row.id)
    ElMessage.success('文章删除成功')
    
    // 刷新列表
    fetchArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用昨天及以前的日期
}

// 快捷时间设置
const setQuickTime = (hours) => {
  const now = new Date()
  const futureTime = new Date(now.getTime() + hours * 60 * 60 * 1000)
  const formattedTime = formatDateToString(futureTime)
  
  selectedPublishTime.value = formattedTime
}

// 检查当前选择的时间是否匹配快捷时间
const isQuickTimeSelected = (hours) => {
  if (!selectedPublishTime.value) return false
  
  // 计算目标时间字符串
  const now = new Date()
  const targetTime = new Date(now.getTime() + hours * 60 * 60 * 1000)
  const targetTimeString = formatDateToString(targetTime)
  
  // 比较字符串（允许1分钟误差，比较到分钟级别）
  const selectedMinute = selectedPublishTime.value.substring(0, 16) // YYYY-MM-DD HH:mm
  const targetMinute = targetTimeString.substring(0, 16)
  
  return selectedMinute === targetMinute
}

// 清除发布时间
const clearPublishTime = () => {
  selectedPublishTime.value = ''
}

// 时间格式化函数
const formatDateToString = (date) => {
  if (!date) return ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 开启文章（显示时间选择对话框）
const handleEnableArticle = (row) => {
  currentEnableArticle.value = row
  selectedPublishTime.value = ''
  publishTimeDialogVisible.value = true
}

// 确认开启文章
const confirmEnableArticle = async () => {
  if (!currentEnableArticle.value) return
  
  try {
    const confirmMessage = selectedPublishTime.value 
      ? `确认在 ${selectedPublishTime.value} 开启文章“${currentEnableArticle.value.title}”吗？`
      : `确认立即开启文章“${currentEnableArticle.value.title}”吗？`
    
    await ElMessageBox.confirm(
      confirmMessage,
      '开启确认',
      {
        confirmButtonText: '确认开启',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 准备请求数据
    const requestData = {
      id: currentEnableArticle.value.id
    }
    
    // 如果有选择发布时间，则添加到请求数据中
    if (selectedPublishTime.value) {
      requestData.publishTime = selectedPublishTime.value
    }
    
    // 调用开启文章接口
    await enableArticle(requestData)
    
    const successMessage = selectedPublishTime.value 
      ? `文章已设置在 ${selectedPublishTime.value} 发布`
      : '文章开启成功'
    
    ElMessage.success(successMessage)
    
    // 关闭对话框并刷新列表
    publishTimeDialogVisible.value = false
    fetchArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开启文章失败:', error)
      ElMessage.error('开启文章失败，请重试')
    }
  }
}

// 关闭文章
const handleDisableArticle = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认关闭文章"${row.title}"吗？关闭后文章状态将变为待发布。`,
      '关闭确认',
      {
        confirmButtonText: '确认关闭',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用关闭文章接口
    await disableArticle(row.id)
    
    ElMessage.success('文章关闭成功')
    
    // 刷新列表
    fetchArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('关闭文章失败:', error)
      ElMessage.error('关闭文章失败，请重试')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchArticleList()
})

// 组件销毁时清理编辑器
onBeforeUnmount(() => {
  const editor = viewerEditorRef.value
  if (editor) {
    editor.destroy()
  }
})
</script>

<style scoped lang="scss">
.article-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    
    .header-actions {
      .el-button {
        margin-left: 10px;
      }
    }
  }
  
  .article-title {
    font-weight: 500;
    color: #303133;
    cursor: pointer;
    
    &:hover {
      color: #409eff;
    }
  }
  
   .action-buttons {
     display: flex;
     gap: 8px;
     align-items: center;
     white-space: nowrap;
     justify-content: center;
     
     .el-button {
       margin: 0;
       font-size: 12px;
       line-height: 1.5;
       padding: 0;
       height: auto;
       min-height: auto;
       
       &.is-link {
         background: transparent;
         border: none;
         text-decoration: none;
         
         &:hover {
           text-decoration: underline;
         }
       }
     }
   }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.el-table) {
    // 表头样式
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: transparent !important;
          border-bottom: 1px solid #ebeef5;
          padding: 8px 0;
          font-weight: 600;
          color: #606266;
        }
      }
    }
    
    // 表体样式
    .el-table__body-wrapper {
      .el-table__body {
        td {
          padding: 8px 0;
          border-right: 1px solid #ebeef5;
          
          &:last-child {
            border-right: none;
          }
        }
      }
      
      .el-table__row {
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
    
    // 边框样式
    &.el-table--border {
      border: 1px solid #ebeef5;
      
      .el-table__inner-wrapper {
        &::before {
          display: none;
        }
      }
    }
  }
  
   :deep(.el-pagination) {
     .el-pagination__total {
       color: #606266;
     }
   }
   
   // 文章详情侧边栏样式
   .article-detail {
     padding: 20px;
     
     .detail-header {
       margin-bottom: 24px;
       border-bottom: 1px solid #ebeef5;
       padding-bottom: 16px;
       
       .article-title-detail {
         margin: 0 0 12px 0;
         color: #303133;
         font-size: 20px;
         font-weight: 600;
       }
       
       .article-meta {
         display: flex;
         align-items: center;
         gap: 16px;
         
         .meta-info {
           color: #909399;
           font-size: 14px;
         }
       }
     }
     
     .article-cover {
       margin-bottom: 24px;
       
       img {
         width: 100%;
         max-width: 400px;
         height: auto;
         border-radius: 8px;
         box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
       }
     }
     
     .article-content {
       .content-title {
         font-size: 16px;
         font-weight: 600;
         color: #303133;
         margin-bottom: 12px;
       }
       
       .editor-container {
         border: 1px solid #dcdfe6;
         border-radius: 4px;
         overflow: hidden;
       }
     }
   }
   
   .loading-container {
     display: flex;
     flex-direction: column;
     align-items: center;
     justify-content: center;
     height: 200px;
     color: #909399;
     
     .el-icon {
       font-size: 24px;
       margin-bottom: 8px;
     }
   }
   
   // 开启文章时间选择对话框样式
   .publish-time-dialog {
     .dialog-content {
       .dialog-tip {
         margin: 0 0 16px 0;
         color: #606266;
         font-size: 14px;
       }
       
       .publish-time-container {
         margin-bottom: 16px;
         
         .custom-datepicker {
           width: 100%;
         }
         
         .quick-time-buttons {
           margin-top: 12px;
           display: flex;
           gap: 8px;
           flex-wrap: wrap;
           
           .el-button {
             margin: 0;
           }
         }
       }
       
       .publish-time-tips {
         p {
           margin: 0;
           color: #909399;
           font-size: 12px;
         }
       }
     }
   }
   
   :deep(.el-dialog__body) {
     padding: 20px;
   }
 }
 </style>

